/**
 * @date: 2025/3/22
 * @author: 小红
 * @Description: 获取操作组件
 */
import { importGlobDefault, stringRemoveSlash } from '@/utils/utils';
import useEmitter from '@/hooks/useEmitter';

type RightComponentType = 'RightAdd';

type LeftComponentType = 'LeftBack';

type CenterComponentType = 'CenterSearch';

type ComponentType = RightComponentType | LeftComponentType | CenterComponentType;

const components = importGlobDefault(
	import.meta.glob('@/layout/main/components/**/*.vue', {
		eager: true,
	}),
);

const reg = new RegExp(/([A-Za-z]+)\.vue$/);

/**
 * 获取组件名称
 * @param name
 */
function getComponentName(name: string) {
	const match = name.match(reg);
	return match?.[1] || name;
}


/**
 * 获取组件映射
 */
function getComponentMap() {
	const componentMap: any = new Map();

	for (let i = 0; i < components.length; i++) {
		const comp = components[i];
		const name = getComponentName(components[i].__file);
		comp['action_key'] = name;
		componentMap.set(name, components[i]);
	}

	return componentMap;
}

const compMap = getComponentMap();

/**
 * 获取操作组件
 * @param key
 */
export function useBarComp(key: ComponentType) {
	return compMap.get(key);
}

export type UseBarCompReturnType = ReturnType<typeof useBarComp>;

/**
 * 使用事件
 * @param Key
 * @param fn
 */
export function useBarAction(Key: ComponentType, fn: () => void) {
	const route = useRoute();

	const eventName = `${stringRemoveSlash(route.path)}${Key}`;

	useEmitter.on(eventName, fn);

	onUnmounted(() => {
		useEmitter.off(eventName, fn);
	});
}
